<template>
  <Card>
    <Button type="primary" class="mb-20px" @click="visible = true">
      <template #icon><PlusOutlined /></template>
      添加品牌</Button
    >
    <Table
      :columns="columns"
      :data-source="trademarklist"
      bordered
      :pagination="{
        current, //当前页码
        pageSize, // 每页总数
        total, //一共多少条
        pageSizeOptions: ['3', '6', '9', '12'], //指定每页可以显示多少条
        showQuickJumper: true, //是否可以快速跳转到某页
        showSizeChanger: true,
        showTotal: () => {
          return `总共${total}条`;
        },
        onChange: currentChange, //页码改变的回调，参数是改变后的页码及每页条数
        onShowSizeChange: pageSizeChange, //pageSize 变化的回调
      }"
      :loading="loading"
    >
      <template #bodyCell="{ column, index, text, record }">
        <!-- 命名插槽加作用域插槽：一共可以接受四个参数，
        text：dataIndex 对应的数据
        record：对应的整条数据
        index：下标
        column  列（columns对应的对象） -->

        <!-- 
          默认列渲染的是dataIndex对应数据的值
          如果指定了下列插槽语法：就会渲染下面的内容
         -->
        <template v-if="column.dataIndex === 'index'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'logoUrl'">
          <img :src="text" :alt="record.tmName" class="w-200px h-120px" />
        </template>
        <template v-if="column.dataIndex === 'operator'">
          <Button
            class="
              !bg-orange-500
              mr-10
              !text-warm-gray-50
              hover:(
              !bg-orange-300
              !border-orange-300)
            "
          >
            <template #icon><HighlightOutlined /></template>
            修改品牌
          </Button>
          <Button danger>
            <template #icon><DeleteOutlined /></template>
            删除品牌
          </Button>
        </template>
      </template>
    </Table>
  </Card>
  <Modal v-model:visible="visible" title="添加品牌" @ok="handleOk">
    <!-- 
      ref="xxx"
       获取组件实例，将来通过form实例来调用表单验证的方法
       配合响应式数据一起使用 const xxx=ref()
       :model="xxx" 绑定表单使用的验证数据
       :rules="xxx"表单验证规则
       :label-col="labelCol"  label文字宽度
      :wrapper-col="wrapperCol" 表单项宽度
     -->
    <Form
      class="!mt-30px !ml-20px"
      ref="formRef"
      :model="trademark"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 14 }"
    >
      <FormItem ref="name" label="品牌名称" name="tmName">
        <Input v-model:value="trademark.tmName" />
      </FormItem>
      <FormItem ref="name" label="品牌Logo" name="logoUrl">
        <!--  v-model:file-list="fileList" 收集图片数据 name=“xxx” 组件自动发动请求获取字段
         list-type：xxx 上传的组件风格 class 样式   :show-upload-list="false" 是否上传图片列表（上传多张图片）
          action 照片要上传的服务器地址 :before-upload="beforeUpload" 上传之前触发的回调函数
          @change="handleChange" 上传过程中触发的回调函数 -->
        <Upload
          list-type="picture-card"
          :show-upload-list="false"
          action="http://39.98.123.211/admin/product/fileUpload"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <!-- 展示上传成功的图片 -->
          <img v-if="trademark.logoUrl" :src="trademark.logoUrl" alt="avatar" />
          <div v-else>
            <!-- 展示上传过程中的图标 -->
            <LoadingOutlined v-if="uploadLoading"></LoadingOutlined>
            <PlusOutlined v-else></PlusOutlined>
          </div>
        </Upload>
        <span class="text-gray-500 text-12px">只能上传jpg/png文件，且不超过500kb</span>
      </FormItem>
    </Form>
  </Modal>
</template>

<script lang="ts">
import { defineComponent, reactive } from 'vue';
//只有定义组件名称才能实现按钮
export default defineComponent({
  name: 'Trademark',
});
</script>



<script lang="ts" setup>
import { getTrademarkListApi, goTrademarkImgApi } from '/@/api/product/trademark';
import { ref, onMounted } from 'vue';
import { recordModelList, RerecordModelList } from '/@/api/product/model/tradeMarkmodel';
import { Button, Card, Table, Modal, Form, FormItem, Input, Upload, message } from 'ant-design-vue';
import {
  PlusOutlined,
  HighlightOutlined,
  DeleteOutlined,
  LoadingOutlined,
} from '@ant-design/icons-vue';
import type { UnwrapRef } from 'vue';
import { FileItem, FileInfo } from './file';
//表格数据
const columns = [
  {
    // 标题
    title: '序号',
    className: 'trademark-number',
    // 渲染数据哪个属性的值
    dataIndex: 'index',
  },
  {
    // 标题
    title: '品牌名称',
    // 渲染数据哪个属性的值
    dataIndex: 'tmName',
  },
  {
    title: '品牌LOGO',
    // className: 'column-money',
    dataIndex: 'logoUrl',
  },
  {
    title: '操作',
    className: 'trademark-operator',
    dataIndex: 'operator',
  },
];
//分页器数据
const current = ref<number>(1); //定义current初始数据类型为number，初始值为1，响应式
const pageSize = ref<number>(3); //每页条数,为三条
const total = ref<number>(30); //总共有多少页
const trademarklist = ref<RerecordModelList>([]);
//表单验证时收集的数据
const trademark: UnwrapRef<recordModelList> = reactive({
  tmName: '', //品牌名称
  logoUrl: '', //品跑logo
});
//默认情况下对话框关闭
const visible = ref<boolean>(false);
//默认情况下，table不显示加载
const loading = ref<boolean>(false);
//获取ref=formRef的实例对象
const formRef = ref();
//表单校检的规则
const rules = {
  //规则名称必须和表单数据的名称一致
  /* required 必须 message 提示名称 trigger失去焦点 */
  //规则名称
  tmName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  logoUrl: [{ required: true, message: '请添加品牌Logo' }],
};
//默认情况下这个加载是不显示的
const uploadLoading = ref<boolean>(false);
//当页面发生变化时，所产生的回调
const currentChange = (current: number, pagesize: number) => {
  GetTrademarkList(current, pagesize);
};
const pageSizeChange = (current: number, pagesize: number) => {
  GetTrademarkList(current, pagesize);
};
//获取品牌分页的函数
const GetTrademarkList = async (page: number, limit: number) => {
  loading.value = true;
  const result = await getTrademarkListApi(page, limit);
  total.value = result.total;
  trademarklist.value = result.records;
  current.value = page;
  pageSize.value = limit;
  loading.value = false;
};
onMounted(() => {
  GetTrademarkList(current.value, pageSize.value);
});
//对话框确认按钮的回调
const handleOk = async () => {
  //首先再次校验表单
  await formRef.value.validate();
  //发送请求数据
  await goTrademarkImgApi(trademark.tmName, trademark.logoUrl);
  //隐藏对话框
  visible.value = false;
  message.success('添加品牌成功');
  //然后发送异步请求，更新trademarklist
  GetTrademarkList(current.value, pageSize.value);
};
const handleChange = (info: FileInfo) => {
  //上传中
  if (info.file.status === 'uploading') {
    uploadLoading.value = true;
    return;
  }
  //上传完成
  if (info.file.status === 'done') {
    uploadLoading.value = false;
    //将上传完成的图片更新到tradmark的imgUrl中
    trademark.logoUrl = info.file.response.data;
  }
  if (info.file.status === 'error') {
    uploadLoading.value = false;
    message.error('上传图片失败');
  }
};
const beforeUpload = (file: FileItem) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('你好只能上传JPG和PNG格式的图片！');
  }
  const isLt2M = file.size / 1024 < 500;
  if (!isLt2M) {
    message.error('图片必须小于500kb！');
  }
  return isJpgOrPng && isLt2M;
};
</script>
<style>
.trademark-number {
  text-align: center !important;
  width: 70px;
}
.trademark-operator {
  width: 300px;
}
</style>

